package com.itheima.utils;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.Map;

public class JwtUtils {
    private static final String key = "itheima";

    /*生成jwt*/
    public static String createJwt(Map<String, Object> map) {

        return Jwts.builder().signWith(SignatureAlgorithm.HS256, key)
                .setClaims(map)
                .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 7))
                .compact();
    }

    /*解析jwt*/
    public static Map<String, Object> parseJwt(String jwt) throws Exception {

        try {
            Jwts.parser().setSigningKey(key).parseClaimsJws(jwt).getBody();
        } catch (Exception e) {
            throw new Exception("token已失效");
        }
        return Jwts.parser().setSigningKey(key).parseClaimsJws(jwt).getBody();
    }

    /*校验jwt*/
    public static boolean checkJwt(String jwt) throws Exception {
        try {
            Jwts.parser().setSigningKey(key).parseClaimsJws(jwt);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
